package com.yuntoyun.codeavatar.app.tool;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.yuntoyun.codeavatar.app.R;
import com.yuntoyun.codeavatar.app.activity.basic.LoginActivity;
import com.yuntoyun.codeavatar.app.fwcore.adapter.DistrictAdapter;
import com.yuntoyun.codeavatar.app.fwcore.core.AppCoreSign;
import com.yuntoyun.fwcore.appext.data.AppData;
import com.yuntoyun.fwcore.config.FwCodeConfig;
import com.yuntoyun.fwcore.model.FwResultJsonDataModel;
import com.yuntoyun.fwcore.plug.network.retrofit.FwOkHttp;
import com.yuntoyun.fwcore.util.FwGsonUtil;
import com.yuntoyun.fwcore.util.FwIntentUtil;
import com.yuntoyun.fwcore.util.FwPopupWindowUtil;
import com.yuntoyun.fwcore.util.FwSoftInputUtil;
import com.yuntoyun.fwcore.util.FwToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.observers.DisposableObserver;

/**
 * 行政工具类
 */
public class DistrictTool {

    private final int gActionProvince = 901;
    private final int gActionCity = 902;
    private final int gActionCounty = 903;

    /**
     * 设置行政区变量
     */
    private FragmentActivity mActivity;
    private LayoutInflater mLayoutInflater;
    private TextView tvw_district;
    private List<DisposableObserver> mSubscriberList;

    private ArrayList<JsonObject> shengObjects = new ArrayList<>();
    private ArrayList<JsonObject> shiObjects = new ArrayList<>();
    private ArrayList<JsonObject> quObjects = new ArrayList<>();
    private DistrictAdapter shengAdapter;
    private DistrictAdapter shiAdapter;
    private DistrictAdapter quAdapter;
    private ViewHolder viewHolder;
    private LinearLayout layoutView;

    private int provinceCode = -1;
    private int cityCode = -1;
    private int countyCode = -1;
    private String provinceName = "";
    private String cityName = "";
    private String countyName = "";

    private PopupWindow mDialogDistrict;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            FwResultJsonDataModel model = (FwResultJsonDataModel) msg.obj;
            if (null == model) {
                return;
            }

            if (FwCodeConfig.CODE_LOGIN_AGAIN == model.getFwStatus()) {
                AppData.clearLoginData();
                FwIntentUtil.builder().startActivity(mActivity, LoginActivity.class, null,
                        new int[]{
                                Intent.FLAG_ACTIVITY_CLEAR_TOP
                        });
                FwToastUtil.builder().makeText("账号已在其他设备登录，请重新登录！");
                return;
            }

            if (FwCodeConfig.CODE_SUCCESSED != model.getFwStatus()) {
                FwToastUtil.builder().makeText(model.getFwMessage());
                return;
            }

            switch (msg.what) {
                case gActionProvince: //省份
                    JsonArray shengList = FwGsonUtil.builder().getJsonArray(model.getFwData(), "list");
                    for (int i = 0; i < shengList.size(); i++) {
                        JsonObject shengOb = FwGsonUtil.builder().getJsonObject(shengList, i);
                        shengObjects.add(shengOb);
                        shengAdapter.notifyDataSetChanged();
                    }
                    break;
                case gActionCity://城市
                    JsonArray shiList = FwGsonUtil.builder().getJsonArray(model.getFwData(), "list");
                    shiObjects.clear();
                    for (int i = 0; i < shiList.size(); i++) {
                        JsonObject shengOb = FwGsonUtil.builder().getJsonObject(shiList, i);
                        shiObjects.add(shengOb);
                        shiAdapter.notifyDataSetChanged();
                    }
                    break;
                case gActionCounty://区县
                    JsonArray quList = FwGsonUtil.builder().getJsonArray(model.getFwData(), "list");
                    quObjects.clear();
                    for (int i = 0; i < quList.size(); i++) {
                        JsonObject shengOb = FwGsonUtil.builder().getJsonObject(quList, i);
                        quObjects.add(shengOb);
                        quAdapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    };

    //======================================================================================

    public DistrictTool(FragmentActivity activity) {
        mActivity = activity;
    }

    public void setInitView(TextView tvwDistrict, List<DisposableObserver> subscriberList) {
        mSubscriberList = subscriberList;
        mLayoutInflater = LayoutInflater.from(mActivity);
        tvw_district = tvwDistrict;

        //加载全国省份数据
        doLoadDistrict(0, gActionProvince);

        //初始化数据
        this.doInitData();
        //选择行政地区
        tvw_district.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                doResetTab(-1);
                if (null != mDialogDistrict) {
                    //关闭键盘
                    FwSoftInputUtil.builder().closeKeybord(mActivity);
                    FwPopupWindowUtil.showPopupWindow(mActivity, mDialogDistrict, tvw_district);
                }
            }
        });
    }

    public int getProvinceCode() {
        return provinceCode;
    }

    public void setProvinceCode(int provinceCode) {
        this.provinceCode = provinceCode;
    }

    public int getCityCode() {
        return cityCode;
    }

    public void setCityCode(int cityCode) {
        this.cityCode = cityCode;
    }

    public int getCountyCode() {
        return countyCode;
    }

    public void setCountyCode(int countyCode) {
        this.countyCode = countyCode;
    }

    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    /**
     * 设置行政区选择
     */

    private void doInitData() {
        layoutView = (LinearLayout) mLayoutInflater.inflate(R.layout.popup_district_bottom, null, false);
        //布局
        viewHolder = new ViewHolder(layoutView);
        //Tabs点击事件
        viewHolder.llt_province_container.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cityCode != -1)
                    doResetTab(0);
            }
        });
        viewHolder.llt_city_container.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    doResetTab(1);
            }
        });
        //列表
        viewHolder.rvw_province.setLayoutManager(new LinearLayoutManager(mActivity));
        viewHolder.rvw_city.setLayoutManager(new LinearLayoutManager(mActivity));
        viewHolder.rvw_county.setLayoutManager(new LinearLayoutManager(mActivity));
        //适配器
        shengAdapter = new DistrictAdapter(R.layout.activity_owner_address_district_option, shengObjects, mActivity);
        shiAdapter = new DistrictAdapter(R.layout.activity_owner_address_district_option, shiObjects, mActivity);
        quAdapter = new DistrictAdapter(R.layout.activity_owner_address_district_option, quObjects, mActivity);
        //省份
        shengAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                JsonObject joItem = shengObjects.get(position);
                provinceCode = FwGsonUtil.builder().getInt(joItem, "code");
                provinceName = FwGsonUtil.builder().getString(joItem, "name");
                //请求数据
                doLoadDistrict(provinceCode, gActionCity);

                //重置数据
                tvw_district.setText("");
                shengAdapter.setSelect(position);
                doSwitchTab(1);
            }
        });
        //城市
        shiAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                JsonObject jsonObject = shiObjects.get(position);
                cityCode = FwGsonUtil.builder().getInt(jsonObject, "code");
                cityName = FwGsonUtil.builder().getString(jsonObject, "name");
                doLoadDistrict(cityCode, gActionCounty);
                shiAdapter.setSelect(position);

                doSwitchTab(2);
            }
        });
        //区县
        quAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                JsonObject jsonObject = quObjects.get(position);
                countyCode = FwGsonUtil.builder().getInt(jsonObject, "code");
                countyName = FwGsonUtil.builder().getString(jsonObject, "name");
                viewHolder.tvw_county.setText(countyName);
                quAdapter.setSelect(position);
                tvw_district.setText(String.format("%s %s %s", provinceName, cityName, countyName));
                mDialogDistrict.dismiss();
            }
        });
        //关联适配器
        viewHolder.rvw_province.setAdapter(shengAdapter);
        viewHolder.rvw_city.setAdapter(shiAdapter);
        viewHolder.rvw_county.setAdapter(quAdapter);
        //弹框
        mDialogDistrict = FwPopupWindowUtil.getPopupWindow(mActivity, layoutView);
        viewHolder.ivw_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDialogDistrict.dismiss();
            }
        });
    }

    private void doResetTab(int tabIdx) {
        if (null == viewHolder) return;

        if (-1 == tabIdx) {
//            viewHolder.llt_province_container.setVisibility(View.VISIBLE);

            shiObjects.clear();
//            viewHolder.llt_city_container.setVisibility(View.INVISIBLE);

            quObjects.clear();
//            viewHolder.llt_county_container.setVisibility(View.INVISIBLE);

            shengAdapter.setSelect(-1);
            viewHolder.tvw_province.setText("选择省份");
            viewHolder.tvw_province.setTextColor(mActivity.getResources().getColor(R.color.appTxtMainColor));
            viewHolder.tvw_province_underline.setBackgroundResource(R.color.appTxtMainColor);

            shiAdapter.setSelect(-1);
            viewHolder.tvw_city.setText("选择城市");
            viewHolder.tvw_city.setTextColor(mActivity.getResources().getColor(R.color.appTxtBlackColor));
            viewHolder.tvw_city_underline.setBackgroundResource(R.color.fw_color_white);

            quAdapter.setSelect(-1);
            viewHolder.tvw_county.setText("选择区县");
            viewHolder.tvw_county.setTextColor(mActivity.getResources().getColor(R.color.appTxtBlackColor));
            viewHolder.tvw_county_underline.setBackgroundResource(R.color.fw_color_white);

            viewHolder.rvw_province.setVisibility(View.VISIBLE);
            viewHolder.rvw_city.setVisibility(View.GONE);
            viewHolder.rvw_county.setVisibility(View.GONE);

            //重置数据
            tvw_district.setText("");

            provinceName = "";
            provinceCode = -1;

            cityName = "";
            cityCode = -1;

            countyName = "";
            countyCode = -1;
        } else if (0 == tabIdx) {
//            viewHolder.llt_province_container.setVisibility(View.VISIBLE);
            shiObjects.clear();
//            viewHolder.llt_city_container.setVisibility(View.INVISIBLE);
            quObjects.clear();
//            viewHolder.llt_county_container.setVisibility(View.INVISIBLE);

            viewHolder.tvw_province.setTextColor(mActivity.getResources().getColor(R.color.appTxtMainColor));
            viewHolder.tvw_province_underline.setBackgroundResource(R.color.appTxtMainColor);

            shiAdapter.setSelect(-1);
            viewHolder.tvw_city.setText("选择城市");
            viewHolder.tvw_city.setTextColor(mActivity.getResources().getColor(R.color.appTxtBlackColor));
            viewHolder.tvw_city_underline.setBackgroundResource(R.color.fw_color_white);

            quAdapter.setSelect(-1);
            viewHolder.tvw_county.setText("选择区县");
            viewHolder.tvw_county.setTextColor(mActivity.getResources().getColor(R.color.appTxtBlackColor));
            viewHolder.tvw_county_underline.setBackgroundResource(R.color.fw_color_white);

            cityName = "";
            cityCode = -1;

            countyName = "";
            countyCode = -1;

            viewHolder.rvw_province.setVisibility(View.VISIBLE);
            viewHolder.rvw_city.setVisibility(View.GONE);
            viewHolder.rvw_county.setVisibility(View.GONE);
        } else if (1 == tabIdx) {
//            viewHolder.llt_province_container.setVisibility(View.VISIBLE);
//            viewHolder.llt_city_container.setVisibility(View.VISIBLE);
            quObjects.clear();
//            viewHolder.llt_county_container.setVisibility(View.INVISIBLE);

            viewHolder.tvw_city.setTextColor(mActivity.getResources().getColor(R.color.appTxtMainColor));
            viewHolder.tvw_city_underline.setBackgroundResource(R.color.appTxtMainColor);

            quAdapter.setSelect(-1);
            viewHolder.tvw_county.setText("选择区县");
            viewHolder.tvw_county.setTextColor(mActivity.getResources().getColor(R.color.appTxtBlackColor));
            viewHolder.tvw_county_underline.setBackgroundResource(R.color.fw_color_white);

            countyName = "";
            countyCode = -1;

            viewHolder.rvw_province.setVisibility(View.GONE);
            viewHolder.rvw_city.setVisibility(View.VISIBLE);
            viewHolder.rvw_county.setVisibility(View.GONE);
        }
    }

    private void doSwitchTab(int tabIdx) {

        boolean isProvince = false;
        boolean isCity = false;
        boolean isCounty = false;

        if (null == viewHolder) return;

        if (1 == tabIdx) {
            isCity = true;
//            viewHolder.llt_province_container.setVisibility(View.VISIBLE);
//            viewHolder.llt_city_container.setVisibility(View.VISIBLE);
//            viewHolder.llt_county_container.setVisibility(View.INVISIBLE);

            viewHolder.tvw_province.setTextColor(mActivity.getResources().getColor(R.color.appTxtBlackColor));
            viewHolder.tvw_province.setText(provinceName);
            viewHolder.tvw_province_underline.setBackgroundResource(R.color.fw_color_white);

            shiAdapter.setSelect(-1);
            viewHolder.tvw_city.setTextColor(mActivity.getResources().getColor(R.color.appTxtMainColor));
            viewHolder.tvw_city.setText("选择城市");
            viewHolder.tvw_city_underline.setBackgroundResource(R.color.appTxtMainColor);

            cityName = "";
            cityCode = -1;

            countyName = "";
            countyCode = -1;
        } else if (2 == tabIdx) {
            isCounty = true;
//            viewHolder.llt_province_container.setVisibility(View.VISIBLE);
//            viewHolder.llt_city_container.setVisibility(View.VISIBLE);
//            viewHolder.llt_county_container.setVisibility(View.VISIBLE);

            viewHolder.tvw_city.setTextColor(mActivity.getResources().getColor(R.color.appTxtBlackColor));
            viewHolder.tvw_city.setText(cityName);
            viewHolder.tvw_city_underline.setBackgroundResource(R.color.fw_color_white);

            quAdapter.setSelect(-1);
            viewHolder.tvw_county.setTextColor(mActivity.getResources().getColor(R.color.appTxtMainColor));
            viewHolder.tvw_county_underline.setBackgroundResource(R.color.appTxtMainColor);
            viewHolder.tvw_county.setText("选择区县");

            countyCode = -1;
            countyName = "";
        }

        //列表设置
        viewHolder.rvw_province.setVisibility((isProvince) ? View.VISIBLE : View.GONE);
        viewHolder.rvw_city.setVisibility((isCity) ? View.VISIBLE : View.GONE);
        viewHolder.rvw_county.setVisibility((isCounty) ? View.VISIBLE : View.GONE);
    }

    private void doLoadDistrict(int parentCode, int what) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("parentCode", parentCode);
        AppCoreSign.addSign(map);
        Observable<FwResultJsonDataModel> observable = FwOkHttp.getFwAPIService().getDistrictList(map);
        FwOkHttp.instance().doPost(mActivity, mHandler.obtainMessage(what), observable, mSubscriberList,
                true);
    }

    static class ViewHolder {

        @BindView(R.id.tvw_province)
        TextView tvw_province;
        @BindView(R.id.tvw_province_underline)
        TextView tvw_province_underline;
        @BindView(R.id.rvw_province)
        RecyclerView rvw_province;
        @BindView(R.id.tvw_city)
        TextView tvw_city;
        @BindView(R.id.tvw_city_underline)
        TextView tvw_city_underline;
        @BindView(R.id.rvw_city)
        RecyclerView rvw_city;
        @BindView(R.id.tvw_county)
        TextView tvw_county;
        @BindView(R.id.tvw_county_underline)
        TextView tvw_county_underline;
        @BindView(R.id.rvw_county)
        RecyclerView rvw_county;
        @BindView(R.id.llt_province_container)
        LinearLayout llt_province_container;
        @BindView(R.id.llt_city_container)
        LinearLayout llt_city_container;
        @BindView(R.id.llt_county_container)
        LinearLayout llt_county_container;
        @BindView(R.id.ivw_close)
        ImageView ivw_close;
        @BindView(R.id.tvw_title)
        TextView tvw_title;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

}
